package com.pospi.pospihold.ui.cash_ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pospi.pospihold.App;
import com.pospi.pospihold.R;
import com.pospi.pospihold.adapter.RefundAdapter;
import com.pospi.pospihold.dao.OrderDao;
import com.pospi.pospihold.dto.OrderBeen;
import com.pospi.pospihold.dto.OrderDto;
import com.pospi.pospihold.greendao.OrderBeenDao;
import com.pospi.pospihold.http.LoadServer;
import com.pospi.pospihold.http.UploadData;
import com.pospi.pospihold.ui.base.BaseActivity;
import com.pospi.pospihold.ui.pay_ui.PayNewActivity;
import com.pospi.pospihold.ui.pay_ui.PayUtil;
import com.pospi.pospihold.util.Api;
import com.pospi.pospihold.util.Constant;
import com.pospi.pospihold.util.GetData;
import com.pospi.pospihold.util.OrderNoUtil;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class RefundActivity extends BaseActivity {

    @Bind(R.id.et_order)
    EditText etOrder;
    @Bind(R.id.lv_order)
    ListView lvOrder;

    private List<OrderBeen> orderDtos;
    private RefundAdapter adapter;
    public static final String REFUNDS = "refunds";
    private List<OrderBeen> beens;
    private String shopid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_refund);
        setTitle("订单列表");
        ButterKnife.bind(this);
        adapteData(GetData.getYYMMDDTime());

        lvOrder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(RefundActivity.this, OrderDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(REFUNDS, orderDtos.get(position));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }

    public void adapteData(String date) {
        orderDtos = App.getInstance().getDaoSession().getOrderBeenDao().
                queryBuilder().where(OrderBeenDao.Properties.SaveDate.eq(date),OrderBeenDao.Properties.ShopNo.eq(SPHelper.getInstance().getString(Constant.SHOP_ID))).list();

        adapter = new RefundAdapter(getApplicationContext(), orderDtos);
        lvOrder.setAdapter(adapter);
    }
    private void update(){
        List<OrderBeen> orderBeens = App.getInstance().getDaoSession().
                getOrderBeenDao().queryBuilder().where(OrderBeenDao.Properties.SaveDate.eq(GetData.getYYMMDDTime()),OrderBeenDao.Properties.ShopNo.eq(SPHelper.getInstance().getString(Constant.SHOP_ID))).list();

        if (orderBeens != null) {
            orderDtos.clear();
            orderDtos.addAll(orderBeens);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        etOrder.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    boolean sd = ((InputMethodManager) etOrder.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    RefundActivity.this.getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapteData(GetData.getYYMMDDTime());
        searchOrder();

    }

    public void searchOrder() {
        beens = App.getInstance()
                .getDaoSession()
                .getOrderBeenDao()
                .queryBuilder()
                .where(OrderBeenDao.Properties.Stutas.eq(UploadData.UP_FAILED),OrderBeenDao.Properties.ShopNo.eq(SPHelper.getInstance().getString(Constant.SHOP_ID)))
                .list();
        if (beens != null) {
            if (beens.size() > 0) {
                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("当前有" + beens.size() + "笔订单未上传，请点击【上传】开始上传")
                        .setPositiveButton("上传", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showLoading("");
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            Thread.sleep(2000);
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    closeLoading();
                                                    update();
                                                }
                                            });

                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }).start();
                                for (OrderBeen been : beens) {
                                    upOrder(been);
                                }
                            }
                        }).setNegativeButton("取消", null).show();
            }

        }
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case PayUtil.UPSUCCESS://上传成功
                    Log.i("up", "上传成功");
                    break;
                case PayUtil.UPFAILED://上传失败
                    Log.i("up", "上传失败");
                    break;
            }
        }
    };
    private void upOrder(final OrderBeen been){
        RequestParams params = UploadData.getUpData(this, been);
        LoadServer.getConnect(this, Api.SYNCORDER, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.d("value", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    if (object.getString("Result").equals("1")) {
                        Message message = Message.obtain();
                        message.what = PayUtil.UPSUCCESS;
                        handler.sendMessage(message);
                        been.setStutas(UploadData.UP_SUCCESS);
                        App.getInstance().getDaoSession().getOrderBeenDao().update(been);
                    } else {
                        Message message = Message.obtain();
                        message.what = PayUtil.UPFAILED;
                        message.obj = object.getString("Message");
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = Message.obtain();
                    message.what = PayUtil.UPFAILED;
                    message.obj = "上传失败";
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = PayUtil.UPFAILED;
                message.obj = "上传失败";
                handler.sendMessage(message);
            }
        });
    }
}